import React,{useState,useEffect} from 'react'
import { Link } from 'react-router-dom'
export default function Carousel() {
  // 轮播广告列表
  let [adList,setAdList]=useState([])
  // 当前显示的轮播广告下标
  let [curAdIndex,setCurAdIndex]=useState(0)
  // 组件挂载 异步请求服务器轮播广告数据
  useEffect(()=>{
    // 应该请求服务器接口数据
    setAdList([
      {aid:8,pic:'./images/banner_01.jpg',href:'/product_details?pid=8'},
      {aid:11,pic:'./images/banner_02.jpg',href:'/product_details?pid=11'},
      {aid:15,pic:'./images/banner_03.jpg',href:'/product_details?pid=15'},
      {aid:16,pic:'./images/banner_04.jpg',href:'/product_details?pid=16'}
    ])
  },[])
  // 生命周期方法 获取轮播数据 开启定时器
  useEffect(()=>{
    let timer=null
    if(adList.length>0){
      let i=0
      timer=setInterval(()=>{
        // console.log(i);
        i++
        i=i>=adList.length?0:i
        setCurAdIndex(i)
      },2000)
    }
    return ()=>{
      if(timer){
        clearInterval(timer)
        timer=null
      }
    }
  },[adList])

  function prev(){
    let i=curAdIndex-1
    i=i<0?adList.length-1:i
    setCurAdIndex(i)
  }
  function next(){
    let i=curAdIndex+1
    i=i>=adList.length?0:i
    setCurAdIndex(i)
  }
  return (
    <div className="banner">
      <ul>
        {
          adList.map((item,i)=>(
            <li key={item.aid} 
            style={{background:`url(${item.pic}) center 0 no-repeat`,
            display:curAdIndex===i?'block':'none',
            zIndex:curAdIndex===i? 20:10}}>
            <Link to={item.href} className="link"></Link>
            </li>
          ))
        }
      </ul>
      {/* 左右箭头*/}
      <span className="cut prev" onClick={prev}></span>
      <span className="cut next" onClick={next}></span>
      {/* 小圆点指示器*/}
      <div className="indicator">
        {
        adList.map((item,i)=>(
          <a key={i} href="#" className={curAdIndex===i?'cur':undefined} onClick={()=>setCurAdIndex(i)}></a>
        ))
        }
      </div>
    </div>
  )
}
